<template>
  <el-form ref="form" label-width="80px">
    <el-form-item label="SPU名称">
      <el-input v-model="spuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择" v-model="(spuInfo.tmId as number)">
        <el-option
          v-for="item in brandList"
          :key="item.id"
          :value="item.id"
          :label="item.tmName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="Spu描述">
      <el-input
        type="textarea"
        rows="4"
        v-model="spuInfo.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="Spu图片">
      <el-upload
        v-model:file-list="(spuImageList as UploadUserFile[])"
        :action="`${baseUrl}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-select
        :placeholder="`还有${unUsedSaleAttrList.length}未选`"
        v-model="data"
      >
        <el-option
          v-for="sales in unUsedSaleAttrList"
          :key="sales.id"
          :value="`${sales.id}:${sales.name}`"
          :label="sales.name"
          >{{ sales.name }}</el-option
        >
      </el-select>
      <el-button
        type="primary"
        size="default"
        icon="ele-Plus"
        :disabled="!data"
        @click="addSalesAttr"
        >添加销售属性</el-button
      >
    </el-form-item>
    <el-form-item>
      <el-table border stripe :data="spuSaleAttrList">
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row }">
            
            <el-tag
              v-for="(tag,index) in row.spuSaleAttrValueList"
              :key="tag.id"
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="row.spuSaleAttrValueList.splice(index,1)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              class="ml-1 w-20"
              size="small"
              ref="editEle"
              v-if="row.isEdit"
              @blur="handleInputConfirm(row)"
              @keyup.enter="handleInputConfirm(row)"
              v-model="row.inputValue"
            />
            <el-button
              class="button-new-tag ml-1"
              size="small"
              v-else
              @click="changeToEdit(row)"
            >
              + New Tag
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row,$index }">
            <el-button type="danger" size="small" icon="ele-Delete" @click="spuSaleAttrList.splice($index,1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button type="default" size="default" @click="emit('setState', 0)"
        >取消</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SpuForm",
});
</script>

<script lang="ts" setup>
import { computed, nextTick, onMounted, ref } from "vue";
import { ElMessage, type UploadProps, type UploadUserFile } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import {
  getBaseSaleAttrListRequest,
  getSaveSpuInfoRequest,
  getUpdateSpuInfoRequest,
  requestSpuImgList,
  requestSpuSaleAttrList,
  type BaseSaleAttrListType,
  type SpuImgListType,
  type SpuInfoType,
  type SpuSaleAttrItemType,
  type SpuSaleAttrListType,
} from "@/api/spu";
import { getAllTmList, type getAllTmListType } from "@/api/product";

//获取自定义事件
const emit = defineEmits<{
  (event: "setState", state: number, row?: SpuInfoType): void;
}>();

//定义临时选择的销售属性
const data = ref("");

//获取props数据
const props = defineProps<{
  spuInfo: SpuInfoType;
}>();

//Spu照片墙的逻辑
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const baseUrl = import.meta.env.VITE_API_URL;

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
//根据新增还是修改去请求当前Form需要的数据(其中新增需要发送:1.品牌列表2.所有销售属性列表,修改需要发送:1.品牌列表2.所有销售属性列表3.当前spu图片列表4.当前spu的属性列表)
//品牌列表
const brandList = ref<getAllTmListType[]>([]);
//所有销售属性列表
const allSalesList = ref<BaseSaleAttrListType>([]);
//当前spu图片列表
const spuImageList = ref<SpuImgListType>([]);
//当前spu的属性列表
const spuSaleAttrList = ref<SpuSaleAttrListType>([]);

//发送品牌列表，所有销售属性列表，当前spu图片列表，当前spu的属性列表请求
const getAllList = async () => {
  if (!props.spuInfo.id) {
    //品牌列表
    const re1 = await getAllTmList();
    brandList.value = re1;
    //所有销售属性列表
    const re2 = await getBaseSaleAttrListRequest();
    allSalesList.value = re2;
  } else {
    //修改逻辑,发送四个请求
    const result1 = getAllTmList();
    const result2 = getBaseSaleAttrListRequest();
    const result3 = requestSpuImgList(props.spuInfo.id);
    const result4 = requestSpuSaleAttrList(props.spuInfo.id);
    try {
      //统一发送
      const result = await Promise.all([result1, result2, result3, result4]);
      brandList.value = result[0];
      allSalesList.value = result[1];
      spuImageList.value = result[2];
      //图片展示逻辑
      spuImageList.value.forEach((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
      spuSaleAttrList.value = result[3];
      //给数据添加isEdit
      spuSaleAttrList.value.forEach((item) => {
        //
        item.isEdit = false;
        //保存输入的内容
        item.inputValue = "";
      });
    } catch (error) {
      ElMessage.error("初始请求失败");
    }
  }
};
onMounted(() => {
  getAllList();
});

//计算allSalesList
const unUsedSaleAttrList = computed(() => {
  return allSalesList.value.filter((item) => {
    return spuSaleAttrList.value.every((item1) => {
      return item1.saleAttrName !== item.name;
    });
  });
});

const addSalesAttr = () => {
  //添加销售属性值事件
  const [baseSaleAttrId, saleAttrName] = data.value.split(":");
  //我们要把数据插入到spuSaleAttrList,所以我们要拼接一个类似的数据格式才能插入
  const tempSpuSaleAttr = {
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName: saleAttrName,
    spuSaleAttrValueList: [],
  };
  //添加到数据中
  spuSaleAttrList.value.push(tempSpuSaleAttr);
  //清空临时数据
  data.value = "";
};

//保存当前的处在编辑模式的表单元素
const editEle = ref<HTMLInputElement>();

//切换编辑模式的事件函数
const changeToEdit = (row: SpuSaleAttrItemType) => {

  row.isEdit = true;
  //
  nextTick(() => {
    editEle.value?.focus();
  });
};

//失去焦点事件
const handleInputConfirm = (row: SpuSaleAttrItemType) => {
  //获取当前输入的值
  let inputValue  = row.inputValue
  //判断当前的内容是否为空
  if(!inputValue?.trim()){
    row.isEdit = false;
    ElMessage.warning("输入不能为空")
    return;
  }

  //判断输入的内容是否有重复
  const isRepeat = row.spuSaleAttrValueList.some(item => {
    return item.saleAttrValueName === inputValue
  })

  if(isRepeat){
    ElMessage.warning("输入有重复");
    row.isEdit = true;
    row.inputValue = ""
    return
  }

  //把值添加列表
  const newSalesAttrValue = {
    baseSaleAttrId:row.baseSaleAttrId,
    saleAttrValueName:row.inputValue as string
  }

  //把newSalesAttrValue添加到spuSaleAttrValueList
  row.spuSaleAttrValueList.push(newSalesAttrValue);
  row.inputValue = ""
  row.isEdit = false;
}

//更新或者修改逻辑
const save = async () => {
  //整理img数据
  const newSpuInfoImg = spuImageList.value.map(item => {
    if(item.response){
      return {
        imgName : item.name as string ,
        imgUrl : item.response.data as string
      }
    }else{
      return{
        imgName : item.imgName,
        imgUrl : item.imgUrl
      }
    }
  })
  props.spuInfo.spuImageList = newSpuInfoImg
  //整理SaleAttrValueList数据
  spuSaleAttrList.value.forEach(item => {
    delete item.isEdit;
    delete item.inputValue;
  });
  props.spuInfo.spuSaleAttrList = spuSaleAttrList.value;

  //发送请求
  try {
    if(props.spuInfo.id){
    await getUpdateSpuInfoRequest(props.spuInfo)
    ElMessage.success("更新成功")
  }else{
    await getSaveSpuInfoRequest(props.spuInfo)
  }
  } catch (error) {
    ElMessage.error("修改成功")
  }

  emit("setState",0)
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
